package com.lindroy.androidplayer.ui.widget

import android.app.Activity
import android.content.Context
import android.util.AttributeSet
import android.view.View
import com.elvishew.xlog.XLog
import com.lindroy.androidplayer.R
import com.lindroy.androidplayer.utils.primaryColor
import com.lindroy.lib_utils.extensions.getResColor
import com.lindroy.lib_utils.extensions.statusbar.setStatusBarDarkMode
import com.lindroy.lib_utils.extensions.statusbar.setStatusBarLightMode
import com.lindroy.lib_utils.extensions.statusbar.setTransParentStatusBar
import com.lindroy.lib_utils.extensions.statusbar.statusBarHeight

/**
 * @author Lin
 * @date 2022/3/4
 * @function 状态栏布局
 */
class StatusBar @JvmOverloads constructor(
    context: Context,
    private val attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : View(context, attrs, defStyleAttr) {

    private val mActivity by lazy { getContext() as Activity }

    private var lightColor = getResColor(R.color.colorWhite)

    private var darkColor = 0

    var isDarkMode = true
        private set

    init {
        //设置透明状态栏，页面布局会延伸到
        setTransParentStatusBar()
        obtainStyledAttrs()
    }

    private fun setTransParentStatusBar() {
        mActivity.setTransParentStatusBar()
    }

    override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec)
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), statusBarHeight)
    }

    private fun obtainStyledAttrs() {
        val typeArray = context.obtainStyledAttributes(attrs, R.styleable.StatusBar)
        darkColor = typeArray.getColor(R.styleable.StatusBar_stb_dark_color, mActivity.primaryColor)
        lightColor = typeArray.getColor(R.styleable.StatusBar_stb_light_color, lightColor)
        setDarkTheme(typeArray.getBoolean(R.styleable.StatusBar_stb_isDarkTheme, true))
        typeArray.recycle()
    }

    private fun setDarkMode(isDarkMode: Boolean) {
        if (isDarkMode) {
            mActivity.setStatusBarDarkMode()
        } else {
            mActivity.setStatusBarLightMode()
        }
    }

    fun setDarkTheme(isDarkTheme: Boolean) {
        isDarkMode = isDarkTheme
        XLog.d("isDarkTheme = $isDarkTheme")
        setDarkMode(isDarkTheme)
        setBackgroundColor(if (isDarkTheme) darkColor else lightColor)
    }

}